package com.zyh.scs.admin.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyh.scs.admin.api.constant.CodeSet;
import com.zyh.scs.admin.api.entity.UserCation;
import com.zyh.scs.admin.base.LaoSheFanWeiResponse;
import com.zyh.scs.admin.mapper.UserCationMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 满客宝 接口请求工具类
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MkbReqUtil {

    @Value("${mannKeBao.merchant_id}")
    public String MERCHANT_ID;

    private final UserCationMapper userCationMapper;

    /**
     * 调用
     *
     * @param url
     * @param data
     * @return
     * @throws Exception
     */
    public LaoSheFanWeiResponse post(String url, String data) {

        UserCation merchantInfo = userCationMapper.selectOne(
                new QueryWrapper<UserCation>()
                        .lambda()
                        .eq(UserCation::getMerchantId, MERCHANT_ID)
        );

        if (null == merchantInfo) {
            log.info("[满客宝接口请求] <<<<<< 商户信息不存在");
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "商户信息不存在");
        }

        String appToken = merchantInfo.getAppId();

        String traceId = UUID.randomUUID().toString().replaceAll("-", "");
        String version = "1.0";
        String timestamp = String.valueOf(System.currentTimeMillis());
        String serialNo = getTradeSerial();

        String sign = com.zyh.scs.admin.utils.UUID.getSign(appToken, MERCHANT_ID, timestamp, version, serialNo);

        log.info("[满客宝接口请求] <<<<<< 开始调用，url: {}, header(traceId: {}, version: {}, timestamp: {}, sign: {}), data: {}",
                url, traceId, version, timestamp, sign, JSON.toJSONString(data));
        HttpResponse response = HttpRequest.post(url)
                .header("content-type", "application/json;charset=UTF-8")
                .header("merchantId", MERCHANT_ID)
                .header("traceId", traceId)
                .header("version", version)
                .header("timestamp", timestamp)
                .header("sign", sign)
                .header("serialNo", serialNo)
                .body(data)
                .execute();
        log.info("[满客宝接口请求] <<<<<< 调用完成，url: {}, header(traceId: {}), reqData: {},statusCode:{},返回报文： {}",
                url, traceId, JSON.toJSONString(data),response.getStatus(), response.body());

        if (HttpStatus.HTTP_OK != response.getStatus()) {
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        String body = response.body();

        if (StrUtil.isEmpty(body)) {
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        JSONObject jsonObject = JSONObject.parseObject(body);

        if (null == jsonObject) {
            return LaoSheFanWeiResponse.error(CodeSet.SYSTEM_ERR_CODE.getCode(), "接口调用失败");
        }

        String errCode = jsonObject.getString("errCode");

        if (StrUtil.isEmpty(errCode) || !"100000".equals(errCode)) {
            return LaoSheFanWeiResponse.error(Integer.valueOf(errCode), "接口调用失败" + response.body());
        }

        return LaoSheFanWeiResponse.success("同步成功");
    }

    public static String getTradeSerial(){
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return sFormat.format(new Date())
                + RandomUtil.randomNumbers(10);
    }

}